import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { isPhone, isEmail } from "@pureadmin/utils";
import {
  getSupplierListApi,
  createSupplierApi,
  updateSupplierApi,
  delSupplierApi,
  getSupplierShowApi
} from "@/api/baseData";
export function usePage() {
  const form = reactive({
    page: 1,
    perPage: 10,
    name: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "supplierId",
      width: 80
    },
	{
	  label: "供应商编码",
	  prop: "code",
	  minWidth: 150
	},
    {
      label: "供应商名称",
      prop: "name",
	  minWidth: 120
    },
    {
      label: "供应商地址",
      prop: "address",
	  minWidth: 160
    },
    {
      label: "联系人姓名",
      prop: "contactName",
	  minWidth: 100
    },
	{
	  label: "联系人手机",
	  prop: "contactPhone",
	  minWidth: 120
	},
	{
	  label: "电子邮箱",
	  prop: "email",
	  minWidth: 140
	},
    {
    	label: "创建者",
    	prop: "createUser.username",
    	minWidth: 100
    },
    {
    	label: "创建时间",
    	prop: "createdAt",
    	minWidth: 160
    },
    {
    	label: "更新者",
    	prop: "updateUser.username",
    	minWidth: 100
    },
    {
    	label: "更新时间",
    	prop: "updatedAt",
    	minWidth: 160
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
	  width: 160
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getSupplierListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.perPage*1;
      pagination.currentPage = 1;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
	console.log(val)
    getSupplierListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
	  pagination.pageSize = result.result.perPage*1;
	  pagination.currentPage = val;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getSupplierListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.perPage*1;
    pagination.currentPage = result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.name = null;
    formEl.resetFields();
    onSearch();
  };
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
		code: 'S' + (new Date()).toLocaleString().replace(/[:/ ]/g, ''),
      };
    } else {
      const res = await getSupplierShowApi({
        supplierId: row?.supplierId
      });
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      formInline.value = {
        title: "修改",
        supplierId: row?.supplierId ?? "",
        name: res?.result?.name ?? "",
        code: res?.result?.code ?? "",
        contactName: res?.result?.contactName ?? "",
        contactPhone: res?.result?.contactPhone ?? "",
        email: res?.result?.email ?? "",
        address: res?.result?.address ?? "",
      };
    }
    addDialog({
      title: `${title}供应商信息`,
      props: {
        formInline: formInline
      },
      width: "44%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了供应商`, {
            type: "success"
          });
          done();
          onSearch();
        }
		if(curData.contactPhone) {
			if(!isPhone(curData.contactPhone)) {
				message("请输入正确的手机号码格式", {
				  type: "error"
				});
				return
			}
		}
		if(curData.email) {
			if(!isEmail(curData.email)) {
				message("请输入正确的邮箱格式", {
				  type: "error"
				});
				return
			}
		}
        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              createSupplierApi(curData)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateSupplierApi(curData)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();
  });

  function handleDelete(row) {
    delSupplierApi({ supplierId: row.supplierId }).then((res) => {
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete
  };
}
